import json

from sqlalchemy.orm import Session
from model.questions import Question
from model.interviews import Interview
from uuid import uuid4, UUID
import logging
import datetime
import aioredis  # 引入异步 Redis 模块
import asyncio

logger = logging.getLogger(__name__)

# 全局 Redis 连接实例（由 main.py 注入）
redis_client = None
redis_pubsub_pool = {}

def init_redis(client: aioredis.Redis):
    global redis_client
    redis_client = client

# 新增全局变量用于保存配置
config = {}


REDIS_EXPIRE_TIME = 3600  # 1小时


async def save_questions_to_db(db: Session, userid: str, resume_id: str, questions_data: list, job_position: str, interview_id: str = None):
    """
    写入 Interview + Questions 到数据库
    :param db: 数据库会话
    :param userid: 用户ID
    :param resume_id: 简历ID
    :param questions_data: AI 生成的问题 JSON 数据
    :param job_position: 面试岗位名称（来自前端请求头或参数）
    """
    try:
        # 如果没有提供 interview_id，则新建一个
        if not interview_id:
            interview_id = uuid4()
            create_interview = True
        else:
            interview_id = UUID(interview_id)
            create_interview = False

        # 可选：检查是否已有该 interview_id 的记录
        existing_interview = db.query(Interview).filter(Interview.interview_id == interview_id).first()
        if create_interview and not existing_interview:
            interview = Interview(
                interview_id=interview_id,
                user_id=userid,
                resume_id=resume_id,
                position=job_position,
                start_time=datetime.datetime.now(),
                status="进行中"
            )
            db.add(interview)
            db.flush()

        # 写入问题
        for question in questions_data:
            db_question = Question(
                question_id=uuid4(),  # ✅ 数据库生成的 question_id
                interview_id=interview_id,
                resume_id=resume_id,
                question_text=question.get("context"),
                question_type=question.get("type"),
                difficulty_level=int(question.get("score", 0)) // 2,
                question_order=question.get("id")  # ✅ 从 JSON 数据中取出 id 作为排序字段
            )
            db.add(db_question)

            # 构建要存储到 Redis 的问题信息（排除 question_order）
            question_info = {
                "question_id": str(db_question.question_id),
            }
            # 序列化并写入 Redis
            question_key = f"interview:{interview_id}:question:{question['id']}"
            asyncio.create_task(redis_client.setex(
                question_key,
                REDIS_EXPIRE_TIME,
                json.dumps(question_info, ensure_ascii=False)  # 确保中文正常显示
            ))

        # ✅ 新增：将问题总数存入 Redis
        total_questions_key = f"interview:{interview_id}:question"
        asyncio.create_task(redis_client.setex(
            total_questions_key,
            REDIS_EXPIRE_TIME,
            str(len(questions_data))
        ))
        db.commit()
        print(f"成功保存 {len(questions_data)} 个问题及一场面试记录")
        logger.info(f"成功保存 {len(questions_data)} 个问题及一场面试记录")

    except Exception as e:
        db.rollback()
        logger.error(f"写入数据库失败: {e}")
